const {Bike, Brand, Op, AppletBikeScore} = require('../db/seq')

class BikeServe {
    async getBikeListServe(ctx) {
        const {pageSize = 10, pageNum = 1, bikeType, name, brandId} = ctx.request.query;
        const {id: createdByUserId} = ctx.state.user;
        const whereOptArr = []
        const whereOpt = {}
        name && Object.assign(whereOpt, {
            name: {
                // 模糊查询
                [Op.like]: '%' + name.trim().toUpperCase() + '%'
            }
        });
        bikeType && Object.assign(whereOpt, {
            bikeType: {
                // 模糊查询
                [Op.like]: '%' + bikeType.trim() + '%'
            }
        });
        brandId && Object.assign(whereOpt, {
            brandId
        });
        createdByUserId && createdByUserId !== 2 && Object.assign(whereOpt, {
            createdByUserId
        });
        whereOptArr.push({...whereOpt})
        const offset = (pageNum - 1) * pageSize;
        const {count, rows} = await Bike.findAndCountAll({
            attributes: {exclude: ['deletedTime', 'createdByUserId', 'detailParams']},
            where: whereOptArr.length > 1 ? {
                [Op.and]: [
                    ...whereOptArr
                ]
            } : whereOpt,
            //分页
            offset,
            //限制
            limit: Number(pageSize),
            order: [
                ['createdTime', 'DESC']
            ]
        })
        return {
            total: count,
            data: rows,
            pageNum,
            pageSize
        }
    }

    async addBikeServe(ctx) {
        const {name, marketTime, brandId, price, bikeType, img, detailParams, bikeTags} = ctx.request.body;
        const {id: createdByUserId} = ctx.state.user;
        const res = await Bike.findOne({
            where: {
                name,
            }
        })
        if (res && res.dataValues) {
            throw ({message: '已存在'})
        } else {
            const brand = await Brand.findOne({
                where: {
                    id: brandId
                }
            })
            const res = await Bike.create({
                name,
                marketTime,
                brandId,
                detailParams,
                img,
                price,
                bikeType,
                createdByUserId,
                bikeTags,
                brandName: brand.dataValues.name
            });
            return res.dataValues;
        }
    }

    async updateBikeServe(ctx, id) {
        const {name, marketTime, brandId, price, bikeType, img, detailParams, bikeTags} = ctx.request.body;
        const {id: createdByUserId} = ctx.state.user;
        const brand = await Brand.findOne({
            where: {
                id: brandId
            }
        })
        const bike = await Bike.findOne({
            where: {
                name,
            }
        })
        const res = await Bike.update({
            name,
            marketTime,
            brandId,
            img,
            price,
            bikeType,
            detailParams,
            createdByUserId,
            bikeTags,
            brandName: brand.dataValues.name
        }, {
            where: {id}
        });
        return res[0] > 0;
    }

    async getBikeByIdServe(id, isApplet) {
        let sqlParams = {
            attributes: {exclude: ['deletedTime', 'createdByUserId']},
            where: {
                id
            },
        }
        if (isApplet) {
            sqlParams.include = {
                model: AppletBikeScore,
                attributes: {
                    exclude: ['createdTime', 'updatedTime', 'userId'],
                }
            }
        }
        const res = await Bike.findOne({...sqlParams})
        return res ? res.dataValues : null
    }

    async updateBikeStatusServe(id, status) {
        const res = await Bike.update({
            status
        }, {
            where: {
                id
            }
        })
        return res[0] > 0
    }

    async updateBikeScoreServe(id, score) {
        const res = await Bike.update({
            score,
            isScored: true
        }, {
            where: {
                id
            }
        })
        console.log(res)
        return res[0] > 0
    }

    async deleteBikeServe(id) {
        const res = await Bike.destroy({
            where: {
                id
            }
        });
        return res > 0;
    }

    async getBikeListByBrandIdServe(ctx) {
        const {brandId, pageSize = 10, pageNum = 1} = ctx.request.query;
        const offset = (pageNum - 1) * pageSize;
        const {count, rows} = await Bike.findAndCountAll({
            where: {
                brandId,
                status: true
            },
            offset,
            limit: Number(pageSize),
            attributes: {exclude: ['deletedTime', 'createdByUserId', 'detailParams']},
        })
        return {
            total: count,
            data: rows,
            pageNum,
            pageSize
        }
    }

    async getBikeScoreRanKeListServe() {
        const res = await Bike.findAll({
            order: [
                ['score', 'Desc']
            ],
            where: {
                isScored: true
            },
            attributes: {
                include: ['id', 'score', 'brandName', 'name', 'img']
            }
        })
        return res
    }

    async getRecentlyUpdatedListServe() {
        const res = await Bike.findAll({
            order: [
                ['createdTime', 'Desc']
            ],
            attributes: {
                include: ['id', 'brandName', 'name', 'img']
            },
            where: {
                status: true
            },
            offset: 0,
            limit: 5
        })
        return res
    }

    async getIndividualizationListServe(ctx) {
        // frame 车架,
        // frontFork 前叉
        // wheelSet 轮组
        // brake 刹车
        // variableSpeed 变速
        const {pageSize = 10, pageNum = 1, frame, frontFork, wheelSet, brake, variableSpeed} = ctx.request.query;
        let bikeTags = []
        frame && frame === 'true' && bikeTags.push(2)
        wheelSet && wheelSet === 'true' && bikeTags.push(3)
        frontFork && frontFork === 'true' && bikeTags.push(4)
        brake && bikeTags.push(Number(brake))
        variableSpeed && variableSpeed === 'true' && bikeTags.push(9)
        const offset = (pageNum - 1) * pageSize;
        const {count, rows} = await Bike.findAndCountAll({
            attributes: {exclude: ['deletedTime', 'createdByUserId', 'detailParams']},
            where: {
                bikeTags: bikeTags.join(',')
            },
            //分页
            offset,
            //限制
            limit: Number(pageSize),
            order: [
                ['createdTime', 'DESC']
            ]
        })
        // console.log(rows)
        return {
            total: count,
            data: rows,
            pageNum,
            pageSize
        }
    }
}

module.exports = new BikeServe();
